package com.magenta.maxoptra.gis;

import java.io.Serializable;

/**
 * @author Sergey Grachev
 */
public final class GeoProviderStatus implements Serializable {

    private static final long serialVersionUID = 4612065718657361819L;

    private final static GeoProviderStatus IDLE = new GeoProviderStatus(State.IDLE, 0, false);
    private final static GeoProviderStatus IDLE_AFTER_UPDATE = new GeoProviderStatus(State.IDLE, 0, true);
    private final static GeoProviderStatus ERROR = new GeoProviderStatus(State.ERROR, 0, true);

    private final State providerState;
    private final boolean wasRequestToProvider;
    private final long expired;

    private GeoProviderStatus(State providerState, long expired, boolean wasRequestToProvider) {
        this.providerState = providerState;
        this.expired = expired;
        this.wasRequestToProvider = wasRequestToProvider;
    }

    public static GeoProviderStatus newBusy(final long expired) {
        return new GeoProviderStatus(State.BUSY, expired, false);
    }

    public static GeoProviderStatus idle() {
        return IDLE;
    }

    public static GeoProviderStatus idleAfterRequest() {
        return IDLE_AFTER_UPDATE;
    }

    public static GeoProviderStatus error() {
        return ERROR;
    }

    public boolean isProviderStillBusy() {
        return State.BUSY.equals(providerState) && System.currentTimeMillis() < expired;
    }

    public boolean isProviderBusy() {
        return State.BUSY.equals(providerState);
    }

    public boolean isProviderError() {
        return State.ERROR.equals(providerState);
    }

    public boolean isProviderIdle() {
        return State.IDLE.equals(providerState);
    }

    public boolean isWasRequestToProvider() {
        return wasRequestToProvider;
    }

    @Override
    public String toString() {
        return "GeoProviderStatus{" +
                "providerState=" + providerState +
                ", wasRequestToProvider=" + wasRequestToProvider +
                ", expired=" + expired +
                '}';
    }

    public static enum State {
        IDLE, BUSY, ERROR
    }
}
